package com.qianfeng.bob.xiexiaobo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.qianfeng.bob.xiexiaobo.R;
import com.qianfeng.bob.xiexiaobo.adapter.QsContentAdapter;
import com.qianfeng.bob.xiexiaobo.bean.QsEntity;
import com.qianfeng.bob.xiexiaobo.config.NetConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bob on 2015/12/16.
 */
public class CommunityContentFragment extends  BaseFragment {
    private PullToRefreshListView mRefreshListView;
    private List<QsEntity.ItemsEntity> datas ;
    private QsContentAdapter adapter;
    private int curPostion;

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_community,container,false);
        initView(view);
        initData();
        return view ;
    }
    private void initData(){
        datas=new ArrayList<>();

        adapter = new QsContentAdapter(datas,getActivity());

        mRefreshListView.setAdapter(adapter);
        mRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);

        mRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mRefreshListView.setPullLabel("下拉刷新");
        mRefreshListView.setReleaseLabel("放开开始刷新");
        mRefreshListView.setRefreshingLabel("正在为您拼命加载.....");

        mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                datas.clear();
                adapter.notifyDataSetChanged();
                curPostion = 0;
                loadDatas();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadDatas();
            }
        });
        loadDatas();
    }


    private void loadDatas() {
        getString(String.format(NetConfig.URL_TEXT, curPostion++), new StringCallBack() {
            @Override
            public void getString(String content) {
                Gson gson = new Gson();

                QsEntity qsEntity = gson.fromJson(content, QsEntity.class);

                datas.addAll(qsEntity.getItems());
                adapter.notifyDataSetChanged();

                mRefreshListView.onRefreshComplete();

            }

            @Override
            public void getStringField() {
                mRefreshListView.onRefreshComplete();
            }
        });
    }


    private void initView(View view) {
        mRefreshListView = ((PullToRefreshListView) view.findViewById(R.id.lv_community));
    }

}
